package cn.sciento.core.endpoint.client;


import cn.sciento.core.common.Configurable;
import cn.sciento.core.common.Configurer;
import cn.sciento.core.endpoint.HttpRequest;
import cn.sciento.core.endpoint.HttpTransporter;
import cn.sciento.core.net.RequestHeaderCopyInterceptor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class BaseHttpTransporter<T> implements HttpTransporter<T>, Configurable<RestTemplate> {
  private final RestTemplate restTemplate;
  
  public BaseHttpTransporter() {
    this.restTemplate = new RestTemplate();
    this.restTemplate.getInterceptors().add(new RequestHeaderCopyInterceptor());
  }
  
  @Override
  public T transport(HttpRequest<T> request) {
    try {
      ResponseEntity<T> responseEntity = this.restTemplate.exchange(request.getSchema() + request.getUrl(), request.getMethod(), request.getHttpEntity(), request.getResponseClass());
      if (responseEntity.getStatusCode().is2xxSuccessful()) {
        return (T)responseEntity.getBody();
      }
      throw new RestClientException("http transport failed, response code [" + responseEntity.getStatusCode() + "]");
    } catch (RuntimeException e) {
      throw new RestClientException("http transport failed, cause: " + e.getMessage(), e);
    } 
  }
  
  @Override
  public void configure(Configurer<RestTemplate> configurer) {
    configurer.configure(this.restTemplate);
  }
}
